
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  query.query;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import logger.PoolLogger;

import property.Order;
import utility.ConvertToLower;
import utility.Splitstring;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.GetIdName;

public class Join implements Queryinterface
{
	GetIdName gid;
	String [] buffer1;
	String[] Querybuffer;
	String Query;
	String JOIN ="join";
	String Message;
	String object;
	String typeofreport;
	String LHS="lhs";
	String RHS="rhs";
	String reporton;
	String conditionopeartor="conditionopeartor";
	StringBuffer heading = new StringBuffer(); 
	int index1[];
	int index2[];
	Hashtable<Object, Object> joinmap = new Hashtable<Object, Object>();
	String tablename;
	int indexofbuffer1=-1;
	int indexofbuffer2=-1;
	String key="no$";
	String value="no$";
	String Reportname;
	int MinQuerycount=1;
	Hashtable<Object, Object > Querymap = new Hashtable<Object, Object>();
	String tid;
	int Querycount=1;
	static int MaxQuerycount=1;
	String alies="p_";
	PoolLogger pl;

	public void queryProcess()
	{
		getResult();
	}
	
	
	public String[] executeQuery(){return null;}
	
	
	
	public Join() {
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	public void setObject(String object)
	{
		this.object = object; 
	}
	
	
	
	public void getResult()
	{
		
		String lhs = joinmap.get(LHS).toString().toLowerCase();
		String rhs = joinmap.get(RHS).toString().toLowerCase();
		//if(MaxQuerycount>=Querycount+2 )
		if(MaxQuerycount==Querycount)
		{
			if(Query.indexOf("FROM")==-1)
				Query = Query + "  " +  buffer1[0] + " "  + alies + Querycount +" JOIN " + Querybuffer[0] + " "+alies + (Querycount-1) +" ON (lower(" + ( alies +(Querycount-1) + "."+rhs+")=lower("+ alies +(Querycount) + "."+lhs)  +"))" ;
			else
				Query = Query.substring(0,Query.indexOf("FROM")+4) + "  " +  buffer1[0] + " "  + alies + (Querycount-1) +" JOIN " + Querybuffer[0] + " "+alies + (Querycount) +" ON (lower(" + ( alies +(Querycount) + "."+rhs+")=lower("+ alies +(Querycount-1) + "."+lhs)  +"))" +Query.substring(Query.indexOf("FROM")+4,Query.length()) ;
		}
		else if(MaxQuerycount>=Querycount+2 || Querycount>=3)		
		{	
			String tempquery="";
			tempquery = tempquery + " " +  buffer1[0] + " "  + alies + (Querycount-1)+  " JOIN ( "   ;
			Query= Query.substring(0, Query.indexOf("FROM")+4) + tempquery + Query.substring(Query.indexOf("FROM")+4,Query.length());
			if(Querycount!=1)
				Query = Query.substring(0, Query.indexOf("WHERE")-1) + ") ON (lower(" +  alies +(Querycount-1) + "."+rhs+")=lower("+  alies +(Querycount) + "."+lhs  +")))" +Query.substring(Query.indexOf("WHERE"),Query.length());
			else
				Query = Query.substring(0, Query.indexOf("WHERE")-1) + ") ON (lower(" +  alies +(Querycount-1) + "."+rhs+")=lower("+  alies +(Querycount) + "."+lhs  +"))" +Query.substring(Query.indexOf("WHERE"),Query.length());
		}	
		else
		{	
			try {
				if(Query.indexOf("FROM")!=-1)
//				Query= Query.substring(0, Query.indexOf("FROM")+4) + tempquery + Query.substring(Query.indexOf("FROM")+4,Query.length());
					Query =Query.substring(0, Query.indexOf("FROM")+4) +" "+ Querybuffer[0]+" "+alies+ (Querycount-1) +" JOIN " +buffer1[0]+" "+alies+ (Querycount)   +" ON (lower(" + ( alies+(Querycount-1)+ "."+rhs+")=lower("+alies+ (Querycount) + "."+lhs)  +")) " +  Query.substring( Query.indexOf("FROM")+4,Query.length());
				else	
				    Query = Query + "  " +  buffer1[0] + " "  + alies + Querycount +" JOIN " + Querybuffer[0] + " "+alies + (Querycount-1) +" ON (lower(" + ( alies +(Querycount-1) + "."+rhs+")=lower("+ alies +(Querycount) + "."+lhs)  +"))" ;
			}
			catch (Exception e) 
			{
				 Query = Query + "  " +  buffer1[0] + " "  + alies + Querycount +" JOIN " + Querybuffer[0] + " "+alies + (Querycount-1) +" ON (lower(" + ( alies +(Querycount-1) + "."+rhs+")=lower("+ alies +(Querycount) + "."+lhs)  +"))" ;
			}
		}
		System.out.println(Query);
	
	}

	public String getObject() 
	{
		return object;
	}

	public String[] getbuffer() 
	{
		return buffer1;
	}

	public void initializeData()
	{

		try {
			RecordSearch rs =new RecordSearch();
			Hashtable<Object, Object> table =new Hashtable<Object, Object>();
			table.put("mid", object);
			table.put("td", "null");
			rs.setConditionMap(table);
			String result[] = rs.getArrayFromResultSet();
			for(int i=0;i<result.length;i++)
			{
				String splitresult[] = result[i].split("\t");
				String value = splitresult[Column.pv_index-1];
				if(value.equals("0"))
					value  = splitresult[Column.vt_index-1];
				else
					value = gid.getItem(value);
				joinmap.put(gid.getItem(splitresult[Column.pid_index-1]),value );
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		
	}

	public void initPool()
	{
		gid = new GetIdName();
		JOIN = gid.getId(JOIN);
		conditionopeartor = gid.getId(conditionopeartor);
	}

	public void setbuffer(String[] buffer) 
	{
		this.buffer1 = buffer;
	}
	public int getFieldinbuffer(String buffer,String Field)
	{
		String split[] = buffer.split("\t");
		for(int i=0;i<split.length;i++)
		{	
			
			if(split[i].toLowerCase().equals(Field.toLowerCase()))
				return i;
		}
		return -1;
	}
	 public void getIndexArray()
	 {
		 String split1[] = buffer1[0].split("\t");
		 String split2[] = Querybuffer[0].split("\t");
		 index1 = new int[split1.length];
		 index2 = new int[split2.length-1];
		 int count=0;
		 for(int i=0;i<split1.length;i++)
		 {
			 index1[count] =i;
			 count++;
		 }
		 count=0;
		 for(int i=0;i<split2.length;i++)
		 {
			 if(i!=indexofbuffer2)
			 {
				index2[count] = i;
			 	count++;
			 }	
		 }
	 }

	public String gettablename() 
	{
		return tablename;
	}

	public void setQuerybuffer(String[] Querybuffer) 
	{
		this.Querybuffer =Querybuffer;
	}

	public void settablename(String tablename) 
	{
		this.tablename = tablename;
	}
	public String[] getQuerybuffer() 
	{
		return Querybuffer;
	}


	public void setKey(String key) 
	{
		this.key = key;
	}


	public void setValue(String value) 
	{
		this.value = value;
	}


	public String getkey() 
	{
		return key;
	}


	public String getvalue() 
	{
		return value;
	}


	public String getQueryName() 
	{
		return null;
	}

	public String [] removeDuplicateRecord(String[] buffer)
	{
		Hashtable<Object, Object> table =new Hashtable<Object, Object>();
		for(int i=1;i<buffer.length;i++)
		{
			table.put(buffer[i], "0");
		}
		String newbuffer[] = new String[table.size()+1];
		newbuffer[0] =buffer[0];
		int count=1;
		Enumeration<Object> enumfortable = table.keys();
		while(enumfortable.hasMoreElements())
		{
			newbuffer[count] = enumfortable.nextElement().toString();
			count++;
		}
		return newbuffer;
	}
	public void setQueryName(String QueryName) 
	{
	
		
	}
	public Hashtable<Object, Object> getQueryMap() 
	{
		return Querymap;
	}


	public void setQueryMap(Hashtable<Object, Object> QueryMap) 
	{
		this.Querymap = QueryMap;
	}


	public String gettid() 
	{
		return tid;
	}

	public void settid(String tid) 
	{
		this.tid =tid;	
	}


	public void addReport() 
	{
		getResult();
	}


	public void updateReport() 
	{
		getResult();
	}


	public String getReportname() 
	{
		return Reportname;
	}


	public void setReportName(String Reportname) 
	{
		this.Reportname = Reportname;
	}


	public void setreporton(String reporton) 
	{
	this.reporton =reporton;
	}


	public void setReportmap(Hashtable<Object, Object> ReportMap) 
	{
		
	}

	public void settypeofreport(String typeofreport) 
	{
		this.typeofreport = typeofreport;
	}
	public void setViewObject(String Object,char ch)
	{
		Splitstring sp =new Splitstring();
	    String splitobject[] = sp.split(Object,Character.toString(ch));
	    Order order = new Order();
	    Hashtable<Object, Object>table =order.getSequences(JOIN);
	    for(int j=0;j<table.size();j++)
	    {
		    for(int i=0;i<splitobject.length;i++)
	    	{
	    		joinmap.put(gid.getId(table.get(Integer.toString(j+1)).toString()), splitobject[i]);
	    		j++;
	    	}
	    }
	 }

	@SuppressWarnings("unchecked")
	public void setViewObject(Vector<Object> PropertyMap) 
	{
		try 
		{
			joinmap.putAll((Map<? extends Object, ? extends Object>) PropertyMap.get(0));
			joinmap =ConvertToLower.convertHashKey(joinmap);
		} catch (Exception e) 
		{
			
		}
	}
	
	public void setQuery(String Query)
	{
		this.Query = Query;
	}
	public String getQuery() 
	{
		return Query;
	}	
	public int getcount() 
	{
		return Querycount;
	}	
	public void setCount(int count) 
	{
		Querycount = count;
	}

	public void setMaxcount(int count) 
	{
		if(MaxQuerycount<count)
		    this.MaxQuerycount =count;
	}
	
	public static void main(String[] args) 
	{
		Join join = new Join();
		join.initPool();
		String buffer[] = new String[1];
		buffer[0]="itemreport";
		String Querybuffer[] = new String[1];
		Querybuffer[0]="billreport";
		Hashtable<Object, Object> table =new Hashtable<Object, Object>();
		table.put("lhs", "itemcode");
		table.put("rhs", "item");
		join.setbuffer(buffer);
		join.setQuerybuffer(Querybuffer);
		join.joinmap.putAll(table);
		join.setQuery("SELECT DISTINCT * FROM");
		join.getResult();
	}


	public void buildQuery() 
	{
	  getResult();
	}
	public void setConditionMap(Vector<Object> QueryMap)
	{
		
	}
	
	public void setProcess(String process) 
	{
	
	}


	
}
